package com.novel.service;

import com.novel.mapper.ChapterOrderMapper;
import com.novel.mapper.NovelMapper;
import com.novel.mapper.UserMapper;
import com.novel.pojo.novel.Novel;
import com.novel.pojo.system.ChapterOrder;
import com.novel.pojo.system.User;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class ChapterOrderService {

    @Autowired
    private ChapterOrderMapper chapterOrderMapper;

    @Autowired
    private NovelMapper novelMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 章节购买
     * 1.尝试扣钱
     * 2.添加购买记录
     */
    @Transactional
    public boolean insertChapterOrderRecord(ChapterOrder chapterOrder) {
        //实时获取用户信息
        User user = userMapper.selectByPrimaryKey(chapterOrder.getUserId());
        //判断钱够不够
        if (user.getAmount() < chapterOrder.getCost()) {
            return false;
        }
        //扣钱
        user.setAmount(user.getAmount() - chapterOrder.getCost());
        int count = userMapper.updateByPrimaryKey(user);

        if (count != 1) {
            return false;
        }

        chapterOrder.setBalance(user.getAmount().intValue());

        return chapterOrderMapper.insert(chapterOrder) == 1;
    }

    /**
     * 查询用户的购买记录
     * 也就是传入章节id判断用户是否购买
     */
    public boolean checkUserBuyChapter(String chapterId, String userId) {
        if (StringUtils.isBlank(userId)) {
            return false;
        }
        ChapterOrder record = new ChapterOrder();
        record.setUserId(userId);
        record.setChapterId(chapterId);
        List<ChapterOrder> orderList = chapterOrderMapper.select(record);
        return CollectionUtils.isNotEmpty(orderList);
    }

    /**
     * 判断阅读的人是不是作者
     */
    public boolean checkUserIsAuthor(String novelId, String userId) {

        if (StringUtils.isBlank(novelId) || StringUtils.isBlank(userId)) {
            return false;
        }

        Novel novel = novelMapper.selectByPrimaryKey(novelId);

        return StringUtils.equals(novel.getAuthorId(), userId);
    }
}